import os
import re

XTS_HOME = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
TEMPLATE_LIST = [
    "ohos_moduletest_suite",
    "ohos_js_hap_suite",
    "ohos_js_app_suite",
    "ohos_shell_app_suite",
    "ohos_hap_assist_suite",
    "ohos_app_assist_suite",
    "ohos_sh_assist_suite",
    "group"
]


def find_build_gn_files(root_dir):
    build_gn_files = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        if "lite" in dirpath:
            continue
        if "cpp" in dirpath:
            continue
        for filename in filenames:
            if filename == 'BUILD.gn':
                build_gn_files.append(os.path.join(dirpath, filename))
    return build_gn_files


def extract_xxx_from_build_gn(file_path):
    pattern = re.compile(r'\b(\w+)\("[^"]*"\)\s*{')
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    matches = pattern.findall(content)
    return matches

def extract_template_from_build_gn(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    for tem in TEMPLATE_LIST:
        if tem in content:
            return True
    return False

# 获取BUILD.gn文件中涉及的全部编译模版,以及未匹配成功的BUILD.gn路径
def main1(root_dir):
    build_gn_files = find_build_gn_files(root_dir)
    xxx_set = set()
    missing_structure_files = []

    for file_path in build_gn_files:
        matches = extract_xxx_from_build_gn(file_path)
        if matches:
            xxx_set.update(matches)
        else:
            missing_structure_files.append(file_path)

    print("xxx_set:")
    print("\n".join(xxx_set))
    print()
    print("missing_structure_files:")
    print("\n".join(missing_structure_files))

# 检查是否有list外的模版
def main2(root_dir):
    build_gn_files = find_build_gn_files(root_dir)
    missing_structure_files = []

    for file_path in build_gn_files:
        if extract_template_from_build_gn(file_path):
            continue
        else:
            missing_structure_files.append(file_path)
    print("missing_structure_files:")
    print("\n".join(missing_structure_files))


if __name__ == '__main__':

    # 当前目录
    current_dir = os.path.join(XTS_HOME, "acts")

    # 执行主函数
    main2(current_dir)